<template>
  <div ref="barChart" style="width: 100%; height: 400px"></div>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import type { EChartsType } from 'echarts/core'
// 按需导入 ECharts 需要的组件
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  ToolboxComponent, // ⬅ 工具栏组件
  DataZoomComponent, // ⬅ 区域缩放组件（给 toolbox 的 dataZoom 用）
  BrushComponent // ⬅ 刷选组件（给 toolbox 的 brush 用）
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

const chartsList = [BarChart, LineChart, PieChart]
// 注册所有需要的组件
echarts.use([
  TitleComponent,
  LegendComponent,
  TooltipComponent,
  GridComponent,
  CanvasRenderer,
  ToolboxComponent,
  DataZoomComponent,
  BrushComponent,
  ...chartsList
])

const props = defineProps({
  option: {
    type: Object
  }
})

// 创建对 DOM 元素的引用
const barChart = ref()
let chartInstance: EChartsType | null = null
// 在组件挂载时初始化图表
onMounted(async () => {
  chartInstance = echarts.init(barChart.value)
  //@ts-ignore
  chartInstance?.setOption(props.option)

  // echarts 监听到 窗口宽度改变，则 echarts 宽度也要改变
  window.addEventListener('resize', () => {
    chartInstance?.resize()
  })
})

onBeforeUnmount(() => {
  // if (chartInstance) {
  chartInstance?.off() // 解绑所有事件（若绑定过）
  chartInstance?.dispose() // 释放实例
  chartInstance = null
  // }

  window.removeEventListener('resize', () => {
    chartInstance?.resize()
  })
})

watch(
  () => props.option,
  async (val) => {
    chartInstance?.clear()
    // @ts-ignore
    chartInstance?.setOption(props.option)
  },
  { deep: true }
)

defineExpose({
  chartInstance
})
</script>

<style scoped>
/* 样式可以根据需要修改 */
</style>